package com.k4rthik.clipall.clipb;

import com.k4rthik.clipall.commons.Logger;
import com.k4rthik.clipall.network.NetworkOps;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import java.io.IOException;

/**
 * Created by IntelliJ IDEA.
 * User: k4rthik
 * Date: 3/25/12
 * Time: 1:44 PM
 */

public class PollingClipboardListener extends Thread
{
    private final Clipboard clipB = Toolkit.getDefaultToolkit().getSystemClipboard();

    @Override public void run()
    {
        Logger.log("Current Clipboard contents:\n" + ClipOps.getClipboardText(clipB));
        Logger.log("Listening for Clipboard changes.");

        long startTime = System.currentTimeMillis();
        Transferable oldContents = clipB.getContents(null);
        while((System.currentTimeMillis() - startTime) < 20000)
        {
            Transferable newContents = clipB.getContents(null);
            if(! ClipOps.getClipboardText(oldContents).equals(ClipOps.getClipboardText(newContents))) {
                Logger.log("Old clipboard contents:" +ClipOps.getClipboardText(oldContents));
                Logger.log("New clipboard contents:" +ClipOps.getClipboardText(newContents));

                oldContents = newContents;
                
                try
                {
                    NetworkOps.sendClipboardText(ClipOps.getClipboardText(newContents));
                } catch(IOException e) {
                    Logger.log("Failed to share Clipboard text", e);
                }
            }
        }
    }


}
